package exampcom.qw.permissiontools;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static android.os.Build.VERSION_CODES.M;

/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends Fragment {
    private View view;

    private RxPermissions rxPermissions;
    /**
     * 相机权限请求码
     */
    private final int REQUEST_CODE_PERMISSION_CALL = 11;


    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_main, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        rxPermissions = new RxPermissions(getActivity());
        view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Disposable disposable = rxPermissions.request(Manifest.permission.CALL_PHONE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    makeCall();
                                } else {
                                    Toast.makeText(getActivity(), "RX授权失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            }
        });

        view.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkAndRequestCallPermission()) {
                    makeCall();
                } else {
                    Toast.makeText(getActivity(), "默认授权失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 读取电话状态
     * 须 READ_PHONE_STATE
     */
    private void getPhoneStatus() {
        TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
        if (tm == null) {
            return;
        }
        String number = "phone " + tm.getLine1Number() + "\nime" + tm.getImei() + "\nsimSerialNumber" + tm.getSimSerialNumber();
    }

    /**
     * 直接打电话
     * 须 CALL_PHONE
     */
    private void makeCall() {
        Uri uri = Uri.parse("tel:10086");
        Intent callIntent = new Intent(Intent.ACTION_CALL, uri);
        startActivity(callIntent);
    }

    private boolean checkAndRequestCallPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CALL_PHONE)) {
                showExplainDialog();
            } else {
                requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE_PERMISSION_CALL);
            }

            return false;
        }
        return true;
    }

    private void showExplainDialog() {
        new AlertDialog.Builder(getActivity())
                .setTitle("权限解释")
                .setMessage("因为你拒绝了，所以我们无法帮你联系移动客服了，请你点击授予")
                .setPositiveButton("我知道了", null)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE_PERMISSION_CALL);
                    }
                }).create().show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode != REQUEST_CODE_PERMISSION_CALL) {
            return;
        }
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getActivity(), "授权失败", Toast.LENGTH_SHORT).show();
        } else {
            makeCall();
        }
    }

    /**
     * 是否是老的权限系统
     */
    public static boolean isOldPermissionSystem(Context context) {
        int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
        return android.os.Build.VERSION.SDK_INT < M || targetSdkVersion < M;
    }
}
